package com.example.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.common.Result;
import com.example.dto.DelSCartDTO;
import com.example.entity.SCart;
import com.example.service.SCartService;
import com.example.service.SSkuService;
import com.example.vo.SCartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.common.RedisConstant.*;

/**
 * <p>
 * 购物车，平凡计算可采用redis(hash),没有总价因为前端可计算 前端控制器
 * </p>
 *
 * @author zh
 * @since 2024-05-17 03:57:20
 */
@RestController
@RequestMapping("/sCart")
@Slf4j
public class SCartController {

    @Autowired
    private SCartService sCartService;
    @Autowired
    private SSkuService skuService;
    @Autowired
    private RedisTemplate<String, SCart> redisTemplate;

    /**
     * 查询购物车
     */
    @GetMapping("/list")
    public Result<List<SCart>> getCartList(@RequestParam Long userId) {
        log.info("查某人的购物车 userId:{}", userId);
//        这个可以用redis缓存，购物车不经常变动

        List<SCart> sCartVOList = redisTemplate.opsForList().range(CART_KEY_PREFIX + userId, 0, -1);
        if (sCartVOList != null && !sCartVOList.isEmpty()) {
            return Result.success(sCartVOList);
        }

        sCartVOList = sCartService.pageCart(userId);
        if (sCartVOList != null && !sCartVOList.isEmpty()) {
            redisTemplate.opsForList().rightPushAll(CART_KEY_PREFIX + userId, sCartVOList);
            redisTemplate.expire(CART_KEY_PREFIX + userId, CART_KEY_EXPIRE, TimeUnit.SECONDS);
        }

        return Result.success(sCartVOList);
    }

    /**
     * 删除购物车商品
     *
     * @param userId
     * @param id
     * @return
     */
    @DeleteMapping
    public Result<?> deleteCart(@RequestParam Long userId, @RequestParam Long id) {
        log.info("删除购物车商品 userId:{},id:{}", userId, id);
        LambdaQueryWrapper<SCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SCart::getUserId, userId).eq(SCart::getId, id);
        sCartService.remove(wrapper);
        redisTemplate.delete(CART_KEY_PREFIX + userId);
        List<SCart> sCartList = sCartService.pageCart(userId);
        if (sCartList != null && !sCartList.isEmpty()) {

            redisTemplate.opsForList().rightPushAll(CART_KEY_PREFIX + userId, sCartList);
            redisTemplate.expire(CART_KEY_PREFIX + userId, CART_KEY_EXPIRE, TimeUnit.SECONDS);
        }
        return Result.success();
    }

    /**
     * 新增到购物车
     */
    @PostMapping
    public Result<?> addCart(@RequestBody SCart cart) {
        log.info("添加购物车 userId:{},商品名:{}", cart.getUserId(), cart.getSpuName());
        redisTemplate.delete(CART_KEY_PREFIX + cart.getUserId());
        //先查询购物车中是否已经存在，若存在则修改count即可
        QueryWrapper<SCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SCart::getUserId, cart.getUserId()).eq(SCart::getSpuId, cart.getSpuId());
        SCart cartDB = sCartService.getOne(queryWrapper);
        if (cartDB != null) {
            cartDB.setCount(cartDB.getCount() + cart.getCount());
            sCartService.updateById(cartDB);
        } else {
            sCartService.save(cart);
        }
        return Result.success("新增成功");
    }

    /**
     * 批量删除
     *
     * @return
     */
    @PostMapping("/deleteBatch")
    public Result<?> deleteCartBatch(@RequestBody DelSCartDTO delSCartDTO) {
        log.info("删除购物车商品 ids:{}", delSCartDTO);
        redisTemplate.delete(CART_KEY_PREFIX + delSCartDTO.getUserId());
        if (!delSCartDTO.getIds().isEmpty()) {
            sCartService.removeBatchByIds(delSCartDTO.getIds());
        }
        List<SCart> sCartList = sCartService.pageCart(delSCartDTO.getUserId());
        if (sCartList != null && !sCartList.isEmpty()) {
            redisTemplate.opsForList().rightPushAll(CART_KEY_PREFIX + delSCartDTO.getUserId(), sCartList);
            redisTemplate.expire(CART_KEY_PREFIX + delSCartDTO.getUserId(), CART_KEY_EXPIRE, TimeUnit.SECONDS);
        }
        return Result.success();
    }

    @GetMapping("/count")
    public Result<?> countChange(@RequestParam Long id, @RequestParam Long userId, @RequestParam Integer count) {
        log.info("修改购物车商品数量 id:{},userId{},count:{}", id, userId, count);
        LambdaUpdateWrapper<SCart> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SCart::getId, id).set(SCart::getCount, count);
        sCartService.update(wrapper);
        redisTemplate.delete(CART_KEY_PREFIX + userId);
        List<SCart> sCartList = sCartService.pageCart(userId);
        if (sCartList != null && !sCartList.isEmpty()) {
            redisTemplate.opsForList().rightPushAll(CART_KEY_PREFIX + userId, sCartList);
            redisTemplate.expire(CART_KEY_PREFIX + userId, CART_KEY_EXPIRE, TimeUnit.SECONDS);
        }
        return Result.success();
    }
}
